//Page Object
var dateTimePicker = require('../../utils/dateTimePicker.js');
const db = wx.cloud.database()
Page({
  data: {
    date: '2020-07-01',
    time: '12:00',
    dateTimeArray: null,
    dateTime: null,
    dateTimeArray1: null,
    dateTime1: null,
    startYear: 2020,
    endYear: 2050
  },

  onLoad: function () {
    // 获取完整的年月日 时分秒，以及默认显示的数组
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    var obj1 = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);

    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray,
      dateTimeArray1: obj1.dateTimeArray,
      dateTime1: obj1.dateTime
    });
  },
  bindDateChange: function (e) {
    var that = this;
    that.setData({
      date: e.detail.value
    })
    console.log(that.data.date);
  },
  //提交信息
  formSubmit: function (e) {
    //表单校验
    if (!this.checkForm(e)) {
      return false;
    }
    var formData = e.detail.value;
    wx.showLoading({
      title: '预约中',
      mask: true
    })

    // 存入到云数据库
    db.collection('book').add({
      data: {
        ...formData,
        createTime: db.serverDate()//服务端的时间
      }
    }).then(res => {
      wx.hideLoading()
      wx.showToast({
        title: '预约成功',
      })

    }).catch(err => {
      wx.hideLoading()
      wx.showToast({
        title: '预约失败',
      })
    })

  },

  formBindsubmit: function (e) {
    if (e.detail.value.username.length == 0 || e.detail.value.phone.length == 0) {
      wx.showToast({
        title: '姓名或电话不为空',
        icon: 'loading',
        duration: 1000,
        mask: true
      })
    }
  },
  checkForm: function (e) {
    if (e.detail.value.username.length == 0) {
      wx.showToast({
        title: '姓名不能为空',
        icon: 'loading',
        duration: 1000,
        mask: true
      })
      return false;
    }
    var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (!myreg.test(e.detail.value.phone)) {
      wx.showToast({
        title: '手机号格式有误',
        icon: 'loading',
        duration: 1000,
        mask: true
      })
      return false;
    }
    if (e.detail.value.enterdate.length == 0) {
      wx.showToast({
        title: "请选择日期",
        icon: 'loading',
        duration: 1000,
        mask: true
      })
      return false;
    }
    if (e.detail.value.count.length == 0) {
      wx.showToast({
        title: "请填写人数",
        icon: 'loading',
        duration: 1000,
        mask: true
      })
      return false;
    }
    return true;
  },
  changeDateTime1(e) {
    this.setData({ dateTime1: e.detail.value });
  },
  changeDateTimeColumn1(e) {
    var arr = this.data.dateTime1, dateArr = this.data.dateTimeArray1;
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray1: dateArr,
      dateTime1: arr
    });
  },
});